<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

Class ProxyAction extends NewzanAction
{
	private static $method = array(
			'get', 'post', 'put', 'delete'
		);

	public function index()
	{
		require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
		$path = I('path');
		$test = I('test');
		$params = I('params');
		$method = I('method');
		$res = array(
				'code' => 'error',
				'msg' => 'invalid path'
			);
		try {
			$curl = new Curl();
			$code = RetStatus::OK;
			
			self::checkPath($path);

			self::checkMethod($method);

			switch ($method) {
				case 'get':
					$url = build_url($path, $params);
					break;
				case 'post':
					$url = build_url($path);
					$curl->setOpt(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
					break;
				case 'put':
					$url = build_url($path);
					break;
				case 'delete':
					$url = build_url($path);
					break;
			}
			$result = $curl->$method($url);
			if($curl->httpStatusCode != 200) {
				throw new Exception($result->message, $curl->httpStatusCode);
			}
			$res = array(
				'code' => 'success',
				'result' => $result
			);
			if($test)
				$res['msg'] = $url;
		} catch (Exception $e) {
			$res['msg'] = $e->getMessage();
			if($test)
				$res['action'] = $url;
			$code = $e->getCode();
		}
		
		$this->display_json($res, $code);
	}

	public static function checkPath($path)
	{
		if(strlen($path) == 0)
			throw new Exception("invalid path", RetStatus::PARAM_ERR);
	}

	public static function checkMethod($method)
	{
		if(!$method)
			throw new Exception("undefined method", RetStatus::PARAM_ERR);

		if(!in_array($method, self::$method))
			throw new Exception("invalid method", RetStatus::PARAM_ERR);
	}
}